﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Yottamud_2013_v3_Main.Game_Files;
using Yottamud_Project_V3;

namespace Yottamud_2013_v3_Main
{
    public class GameDataDecoder
    {
        private static string[] _adjectives = { "angry", "big", "fat", "happy",
                                                   "large", "nasty", "fierce", "thin",
                                                   "small", "tall", "short" };

       
        // The _room array will at some point be loaded with every
        private static string[] _room = { "Newhaven, Healer", "Bank of Godfrey", "Town Square", "Curio Shop", "Newhaven, Narrow Path", "Newhaven, Narrow Road" };
       
        public struct ExperienceType
        {
            public UInt64 CurrentExperience;
            public UInt64 NextLevelExperience;
            public UInt64 ExpTilNextLevel;
        }

        public enum ChatType
        {
            Gossips,
            Gangpaths,
            Telepaths
        }
        public struct CommunicationType
        {
            public string Player;
            public string Data;
            public string TimeStamp;
            public ChatType ChatDataType;
            public string RawData;
        }

        public struct StatLineType
        {
            public int CurrentHitPoints;
            public int MaxHitPoints;
            public int CurrentManaPoints;
            public int MaxManaPoints;

        }



        private static int FindCaptialLetter(string iData)
        {
            int foundIndex = 0;

            iData = iData.Reverse().ToString();

            foreach (char letter in iData)
            {
                if (char.IsUpper(letter))
                {
                    return foundIndex;
                }

                foundIndex++;
            }

            return foundIndex;
        }
        
        /// <summary>
        /// RemoveExcessLetters is primaryly used to remove extra letters in exits.
        /// </summary>
        /// <param name="iData">Input the entire exits list.</param>
        /// <returns>Cleaned up directions for processing.</returns>
        private static string RemoveExcessLetters(string iData)
        {
            string output = string.Empty;

           
            foreach (char c in iData)
            {
                if (!char.IsUpper(c))
                {
                    output += c;
                }
            }

            return output;
        }

        public static bool CheckIfDone(string iData)
        {

            bool done = false;


                string[] splitData = Regex.Split(iData, "\r\n");

                foreach (string data in splitData)
                {
                    if (data.Trim() == "")
                    {
                        done = true;
                    }
                    else
                    {
                        return false;
                    }
                }

            

            return done;

        }

        public static StatLineType DecodeStats(string iData)
        {
            StatLineType statData = new StatLineType();

           string hitsPattern = @"Hits:\s*?(\d+)\/(\d+)\s*?Armour Class:\s*?(\d+)\/(\d+)\s*?Thievery:\s*?(\d+)";

           if (iData.Contains("Hits:"))
           {
               Match match = Regex.Match(iData, hitsPattern);

               statData.CurrentHitPoints = int.Parse(match.Groups[1].Value);
               statData.MaxHitPoints = int.Parse(match.Groups[2].Value);
           }
            return statData;
        }

        public static StatLineType DecodeStatline(string iData)
        {
            StatLineType statData = new StatLineType();

            string[] splitData = Regex.Split(iData, "=");
            string hitPoints = "";

            hitPoints = splitData[1].Replace("(Resting)", "");
            hitPoints = hitPoints.Replace("/MA","");
            hitPoints = hitPoints.Replace("]:", "").Trim();

            statData.CurrentHitPoints = int.Parse(hitPoints);

            return statData;

        }

        public static CommunicationType DecodeCommunication(string iData)
        {
            CommunicationType commData = new CommunicationType();




            //while (iData.Contains("\r\n"))
            //{
            //    iData = iData.Replace("\r\n", "");
            //}


            string[] splitData = null;
            string chatData = string.Empty;

            commData.RawData = iData;

            if (iData.Contains("gossips:"))
            {
                 splitData = Regex.Split(iData, "gossips:");
                int cIndex = 0;

                if (splitData[0].Contains("\r\n"))
                {
                    cIndex = splitData[0].LastIndexOf("\r\n");
                    chatData = Regex.Split(iData.Substring(cIndex, iData.Length - cIndex), "\r\n")[1];
                }
                else
                {
                    cIndex = 0;
                    chatData = iData.Substring(0, iData.IndexOf("[HP")).Replace("\r\n", "").Trim();
                }
                


                 commData.ChatDataType = ChatType.Gossips;
            }
            else if (iData.Contains("gangpaths:"))
            {
                splitData = Regex.Split(iData, "gangpaths:");
                commData.ChatDataType = ChatType.Gangpaths;
            }
            else if (iData.Contains("telepaths:"))
            {
                splitData = Regex.Split(iData, "telepaths:");
                commData.ChatDataType = ChatType.Telepaths;
            }

            if (chatData.Length > 0)
            {
                splitData = null;
                splitData = Regex.Split(chatData, "gossips:");

                commData.Player = splitData[0].Trim();
                commData.Data = splitData[1].Trim();
                commData.TimeStamp = DateTime.Now.ToString();
            }

            return commData;
        }

        public static UInt64 DecodeGainExperience(string iData)
        {
            
            string gainExpPattern = @"You gain\s*?(\d+)\s*?experience";

            Match match = Regex.Match(iData, gainExpPattern);

            return UInt64.Parse(match.Groups[1].Value);

        }
        public static string ExtractRoomName(string iData)
        {
            string[] eRoom;

            if (iData.Contains("\r\n"))
            {
                eRoom = Regex.Split(iData, "\r\n");
                return eRoom[1].Trim();
            }
            

            return "Not Found";
        }

        public static ResourceTypes.RoomType FindKnownRoom(string iData, List<string> iExits, List<ResourceTypes.NpcType> npcList)
        {
           
            ResourceTypes.RoomType room = GameResources.FindRoom(iData, iExits, npcList);
      
            return room;
        }

        public static List<string> DecodeExits(string iData)
        {

            List<string> exits = new List<string>();

            iData = iData.Replace("Obvious exits:", "").Replace("[HP", "");
            iData = RemoveExcessLetters(iData);

            while (iData.Contains("\r\n"))
            {
                iData = iData.Replace("\r\n", "");
            }

            if (iData.Contains(","))
            {
                string[] splitExit = iData.Split(',');

                foreach (string exit in splitExit)
                {
                     exits.Add(exit.Trim());
                }
            }
            else // one exit
            {
                exits.Add(iData.Trim());
            }


            return exits;
        }

        private static string RemoveMonsterAdjective(string iMonster)
        {
            foreach (string adjective in _adjectives)
            {
                if (iMonster.Contains(adjective))
                {
                    iMonster = iMonster.Replace(adjective, "").Trim();
                    break;
                }
            }
            return iMonster;
        }

        public static string FixItemData(string[] iData)
        {
            string tData = string.Empty;

            foreach (string sData in iData)
            {
                if (sData.Contains("here."))
                {
                    tData += sData;
                    break;
                }

                tData += sData;
            }

            return tData;
        }

        public static List<ResourceTypes.ItemType> DecodeItemsInRoom(string iData)
        {
            //You notice scroll of magic missile, scroll of blur, torch, small sign here.\r\n
            List<ResourceTypes.ItemType> itemList = new List<ResourceTypes.ItemType>();

            iData = iData.Replace("You notice ", "").Replace("here.", "");

            string[] splitData = Regex.Split(iData, ",");

            return itemList;
        }

        public static ExperienceType DecodeExperience(string iData)
        {
            ExperienceType expData = new ExperienceType();

            string expPattern = @"Exp:\s*?(\d+)\s*?Level:\s*?(\d+)\s*?Exp needed for next level:\s*?(\d+)\s*?\((\d+)\)";

            Match match = Regex.Match(iData, expPattern);

            expData.CurrentExperience = UInt64.Parse(match.Groups[1].Value);
            expData.ExpTilNextLevel = UInt64.Parse(match.Groups[3].Value);
            expData.NextLevelExperience = UInt64.Parse(match.Groups[4].Value);

            return expData;
        }

        public static List<ResourceTypes.NpcType> DecodeNPC(string iData)
        {
            List<string> NPCs = new List<string>();
            List<ResourceTypes.NpcType> monsters = new List<ResourceTypes.NpcType>();

            int npcIndex = 0;

            iData = iData.Replace("Also here:", "").Replace(".", "").Trim();

            if (iData.Contains(","))
            {
                string[] splitHere = iData.Split(',');

                foreach (string npc in splitHere)
                {
                    string tNpc = RemoveMonsterAdjective(npc);

                    NPCs.Add(tNpc.Trim() + "_" + npcIndex++);
                }
            }
            else
            {
                string tNpc = RemoveMonsterAdjective(iData);

                NPCs.Add(tNpc.Trim() + "_" + npcIndex++);
            }

            foreach (string monster in NPCs)
            {
                ResourceTypes.NpcType npc = GameResources.FindNPC(monster.Remove(monster.IndexOf("_")));
                if (npc != null)
                {
                    monsters.Add(npc);
                }
            }

            return monsters;

        }



    }
}
